export const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
// 把纯数字格式化为日期
const formatDate = (str, symbol = '-') => {
  if (!Number(str)) return
  let date = [ str.substr(0, 4), str.substr(4, 2), str.substr(6, 2) ].filter(v => v)
  let time = [ str.substr(8, 2), str.substr(10, 2), str.substr(12, 2) ].filter(v => v)
  let timeStr = time.length ? ' ' + time.join(':') : ''
  return date.join(symbol) + timeStr
}
const objectToString = (obj, isEncode) => {
  if (isEncode) {
    return Object.keys(obj).reduce((arr, v) => {
      if(obj[v] !== undefined){
        arr.push(`${encodeURIComponent(v)}=${encodeURIComponent(obj[v])}`)
      }
      return arr
    }, []).join('&')
  }
  return Object.keys(obj).reduce((arr, v) => {
    if(obj[v] !== undefined){
      arr.push(`${v}=${obj[v]}`)
    }
    return arr
  }, []).join('&')
}

export default {
  formatTime,
  formatDate,
  objectToString
}
